package com.ruoyi.manage.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.manage.mapper.AvatarMapper;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @author ZhangZhongGen
 */
@RestController
@Slf4j
@Api(tags = "头像管理")
@RequestMapping("/manage/avatar")
public class AvatarController extends BaseController {
    @Autowired
    private AvatarMapper avatarMapper;
    @Autowired
    private FileStorageService fileStorageService;
    @GetMapping("/list")
    public TableDataInfo list(){
        return getDataTable(avatarMapper.selectAvatarList());
    }

    @PostMapping
    public AjaxResult add(@RequestParam("file") MultipartFile file) throws IOException {
        String objetcName = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"))+"/";
        FileInfo fileInfo = fileStorageService.of(file)
                .setPath(objetcName) //保存到相对路径下，为了方便管理，不需要可以不写
                .upload();
        avatarMapper.insertAvatar(fileInfo.getUrl());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("url", fileInfo.getUrl());
        ajax.put("fileName", fileInfo.getUrl());//这里的值需要修改成URL,因为前端对http开头的地址不会做路径替换,从而直接显示这个图片
        ajax.put("newFileName", FileUtils.getName(fileInfo.getUrl()));
        ajax.put("originalFilename", file.getOriginalFilename());
        return ajax;
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id){
        avatarMapper.deleteAvatarById(id);
    }
}
